<template>
  <div id="app">
    <header>
      <h2>图书馆里安利</h2>
      <el-button type="primary" size="medium" @click="dialogVisible = true">添加图书</el-button>
    </header>
    <el-table :data="books" style="width: 100%" border stripe>
      <el-table-column prop="id" label="ID" width="100"></el-table-column>
      <el-table-column prop="bookname" label="姓名" width="150"></el-table-column>
      <el-table-column prop="author" label="作者" width="150"></el-table-column>
      <el-table-column prop="publisher" label="出版社" width="150"></el-table-column>
      <el-table-column prop="" label="操作"></el-table-column>
    </el-table>
    <!--添加的弹层-->
    <el-dialog title="提示" :visible.sync="dialogVisible" width="500px">
      <el-form ref="form" label-width="80px">
        <el-form-item label="书名">
          <el-input v-model="row.bookname"></el-input>
        </el-form-item>
        <el-form-item label="作者">
          <el-input v-model="row.author"></el-input>
        </el-form-item>
        <el-form-item label="出版社">
          <el-input v-model="row.publisher"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addbook">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getBooksAPI, addBookAPI } from '@/api/books'

export default {
  data() {
    return {
      dialogVisible: false, // 控制弹框是否显示，默认false不显示
      row: {
        bookname: '',
        author: '',
        publisher: ''
      },
      books: [
        // { id: 1, bookname: '西游记', author: '沙师弟', publisher: '大堂出版社' },
        // { id: 2, bookname: '西游记', author: '沙师弟', publisher: '大堂出版社' },
        // { id: 3, bookname: '西游记', author: '沙师弟', publisher: '大堂出版社' }
      ]
    }
  },
  // 生命周期函数中，当组件创建的时候，立即发送请求
  created() {
    this.getBooks()
  },

  methods: {
    async getBooks() {
      // 调用 getBooksAPI() 得到返回值Promise
      const { data: res } = await getBooksAPI()
      // console.log(res) // 输入服务器返回的结果
      this.books = res.data // 将服务器返回的数据部分，赋值给数据项books
    },
    async addbook() {
      // 调用API方法，添加图书
      const { data: res } = await addBookAPI(this.row)
      // console.log(this.row)
      this.getbooks() // 重新获取全部图书
      this.$message.success(res.message) // 消息提示
      this.dialogVisible = false // 关闭弹出层
    }
  }
}
</script>

<style lang="less">
header {
  height: 60px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
